package com.bjesc_b2c.app.appraiset.base;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.bjesc_b2c.app.appraiset.R;
import com.bjesc_b2c.app.appraiset.RequestAndResultCode;
import com.bjesc_b2c.app.appraiset.adapter.XDdataAdapter;
import com.bjesc_b2c.app.appraiset.bean.DealerCarBean;
import com.bjesc_b2c.app.appraiset.bean.XDPostBean;
import com.bjesc_b2c.app.appraiset.mvp.presenter.XDPresenter;
import com.bjesc_b2c.app.appraiset.mvp.presenter.impl.XDPresenterImpl;
import com.bjesc_b2c.app.appraiset.mvp.view.XDView;
import com.bjesc_b2c.app.appraiset.mvp.view.activity.CarOffShelfActivity;
import com.bjesc_b2c.app.appraiset.mvp.view.activity.PatrolShopActivity;
import com.bjesc_b2c.app.appraiset.mvp.view.fragment.PublishpassFragment;
import com.bjesc_b2c.app.appraiset.utils.CustomSharedPreferences;
import com.bjesc_b2c.app.appraiset.widget.popupwindow.AdjustmentPop;
import com.liaoinstan.springview.container.DefaultFooter;
import com.liaoinstan.springview.container.DefaultHeader;
import com.liaoinstan.springview.widget.SpringView;
import com.orhanobut.logger.Logger;
import com.rxretrofit_build.model.RxBusBean;

import java.util.ArrayList;
import java.util.List;

import master_bean.CarSeriesModelBean;
import rxbus_base.RxBus;
import rxretrofit_base.model.KeyBean;
import rxretrofit_base.model.TokenBean;

/**
 * Created by yidong on 2017/7/26.
 */

public class BaseListFragmen extends BaseFragment implements SpringView.OnFreshListener, XDView, AdjustmentPop.AdjustmencallBack, XDdataAdapter.statusListener {

    RecyclerView recyclerView;
    SpringView springView;
    private XDdataAdapter mAdapter;
    public XDPresenter xdPresenter;
    public String dealerID;
    private String status;
    public int page = 1;
    public int type = 1;
    public String keyWord = "";
    public boolean isLodmore = true;
    public boolean isShowDialog = true;
    private List<DealerCarBean.ListBean> dataList = new ArrayList<DealerCarBean.ListBean>();
    private AdjustmentPop pop;
    private Intent mIntent;
    public boolean isPrepared;
    //标志当前页面是否可见
    public boolean isVisible;
    public XDPostBean bean = new XDPostBean();
    private long start_time;
    private long end_time;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        contentView = inflater.inflate(R.layout.fragment_todayplan, null);
        dealerID = CustomSharedPreferences.getString(getActivity(), KeyBean.DEALER_ID.valueOf(), KeyBean.FILE_NAME.valueOf());
        return contentView;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        isPrepared = true;
        lazyLoad();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        xdPresenter = new XDPresenterImpl(this);
        //懒加载
        if (getUserVisibleHint()) {
            isVisible = true;
            onVisible();
        } else {
            isVisible = false;
            onInvisible();
        }
    }

    protected void onVisible() {
        lazyLoad();
    }

    protected void lazyLoad() {

    }

    protected void onInvisible() {

    }

    @Override
    public void initView() {
        mIntent = new Intent();
        recyclerView = (RecyclerView) contentView.findViewById(R.id.recycler_view);
        springView = (SpringView) contentView.findViewById(R.id.spring_view);
        springView.setListener(this);
        springView.setHeader(new DefaultHeader(getActivity()));
        springView.setFooter(new DefaultFooter(getActivity()));
        springView.setType(SpringView.Type.FOLLOW);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(layoutManager);
    }


    public void setStatus(String sta) {
        status = sta;
    }

    @Override
    public void loadStart() {
        if (isShowDialog)
            showLoading();
    }

    @Override
    public void loadCompleted() {
        cancelLoading();
        if (springView != null)
            springView.onFinishFreshAndLoad();
    }

    @Override
    public void loadFailure() {
        cancelLoading();
        if (springView != null)
            springView.onFinishFreshAndLoad();
    }

    @Override
    public void getDealerCars(DealerCarBean bean) {
//        if (status.equals("PUBLISHPASS")) {
            RxBus.getInstance().sendData(PublishpassFragment.class.getName(), bean);
//        }
        if (bean != null && bean.getList().size() > 0) {
            refreshData(bean.getList());
            isLodmore = true;
        } else {
            if (page == 1) {
                showToast("没有数据");
                mAdapter = null;
                recyclerView.setAdapter(mAdapter);
            } else {
                showToast("没有了");
            }
            isLodmore = false;
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        Logger.d("ToDayPlanFragment");
    }

    private void refreshData(List<DealerCarBean.ListBean> data) {
        if (page == 1) {
            dataList.clear();
        }
        dataList.addAll(data);
        if (mAdapter == null) {
            mAdapter = new XDdataAdapter(getActivity(), R.layout.layout_item_xundian, dataList);
//           mAdapter.setOnItemClickListener(this);
            mAdapter.setSListener(this);
            recyclerView.setAdapter(mAdapter);
        } else {
            mAdapter.refresh(dataList);
        }
    }


    /**
     * 刷新
     */
    @Override
    public void onRefresh() {
        page = 1;
        isShowDialog = false;
        bean.setDealer_id(dealerID);
        bean.setStatus(status);
        bean.setPage(page);
        xdPresenter.getDealerCar(getActivity(), bean);
    }

    /**
     * 上拉加载
     */
    @Override
    public void onLoadmore() {
        if (isLodmore) {
            page++;
            bean.setDealer_id(dealerID);
            bean.setStatus(status);
            bean.setPage(page);
            xdPresenter.getDealerCar(getActivity(), bean);
        } else {
            springView.onFinishFreshAndLoad();
        }
        isShowDialog = false;

    }

    @Override
    public void adjustment(int position) {//调价
        String carid = mAdapter.getDatas().get(position).getCar_id();
        pop = new AdjustmentPop(getActivity(), carid, this);
//      pop.setFocusable(false);
        pop.showAtLocation(pop.getContentView(), Gravity.TOP, 0, 0);
    }

    @Override
    public void adjustmenSuccess(CarSeriesModelBean cbean) {//调价成功回调
        if (pop != null && pop.isShowing()) {
            pop.dismiss();
        }
        showToast("调价成功！");
        page = 1;
        bean.setPage(page);
        xdPresenter.getDealerCar(getActivity(), bean);
    }

    @Override
    public void panKuSuccess(TokenBean bean) {

    }

    @Override
    public void unusual(int position) {
        String carid = mAdapter.getDatas().get(position).getCar_id();
        xdPresenter.carUnusual(getActivity(), dealerID, carid);
    }

    @Override
    public void offShelf(int position) {
        Intent intent = new Intent(getActivity(), CarOffShelfActivity.class);
        intent.putExtra("Car_id", mAdapter.getDatas().get(position).getCar_id());
        Logger.d("Car_id===== " + mAdapter.getDatas().get(position).getCar_id());
        startActivityForResult(intent, RequestAndResultCode.SelectCarBrandActivity_ResultCode);
    }


    @Override
    protected void doOnNext(RxBusBean rxBusBean) {
        Logger.d("PatrolShopActivity");
//        super.doOnNext(rxBusBean);
        if (!isVisible || !isPrepared) {
            return;
        }
        if (rxBusBean.getRequestMark().equals(PatrolShopActivity.class.getName())) {
            Logger.d("PatrolShopActivity");
            Logger.d("isVisible===" + isVisible + "isPrepared===" + isPrepared);
            if (rxBusBean.getO() instanceof Intent) {
                isShowDialog = true;
                page = 1;
                type = ((Intent) rxBusBean.getO()).getIntExtra("type", 1);
                keyWord = ((Intent) rxBusBean.getO()).getStringExtra("keyWord");
                bean.setDealer_id(dealerID);
                bean.setStatus(status);
                bean.setType(type);
                bean.setKeyword(keyWord);
                xdPresenter.getDealerCar(getActivity(), bean);
            }
        } else if (rxBusBean.getRequestMark().equals("keyWord")) {
            keyWord = rxBusBean.getO().toString();
            bean.setKeyword(keyWord);
        } else if (rxBusBean.getRequestMark().equals("start_time")) {
            start_time = (long) rxBusBean.getO();
            bean.setStart_time(start_time + "");
        } else if (rxBusBean.getRequestMark().equals("end_time")) {
            Logger.d("end_time==" + end_time);
            end_time = (long) rxBusBean.getO();
            isShowDialog = true;
            bean.setEnd_time(end_time + "");
            if (!isVisible || !isPrepared) {
                return;
            } else {
                xdPresenter.getDealerCar(getActivity(), bean);
            }
        }
    }
}